package com.jvyou.mybatis.builder.tags;

import com.jvyou.mybatis.session.Configuration;
import lombok.AllArgsConstructor;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 橘柚
 * @version 1.0-SNAPSHOT
 * @Date 2024/7/8 18:29
 * @Description mapper相关配置
 */
@Deprecated
@AllArgsConstructor
public class MappersNode implements XmlConfigNode {

    /*相对于类路径的资源引用的XMLMapper*/
    private List<String> resources;

    /*相对于类路径的jar包内的映射器接口*/
    private List<String> clazzList;

    /*将包内的映射器接口全部注册为映射器(xml和类)*/
    private List<String> packages;

    private Element element;

    public MappersNode(Element element) {
        this.element = element;
    }

    @Override
    public Configuration apply(Configuration configuration) {
        List<String> resources = getElementAttributeTexts(element, "mapper", "resource");
        List<String> clazzList = getElementAttributeTexts(element, "mapper", "class");
        List<String> packages = getElementAttributeTexts(element, "package", "name");
        this.resources = resources;
        this.clazzList = clazzList;
        this.packages = packages;
        configuration.setMappersNode(this);
        return configuration;
    }

    /**
     * 获取父元素中指定名称的子元素的指定属性值
     *
     * @param parentElement    父元素
     * @param childElementName 子元素的名称
     * @return 子元素文本内容的集合
     */
    private List<String> getElementAttributeTexts(Element parentElement, String childElementName, String attributeName) {
        List<String> texts = new ArrayList<>();
        List<Element> childElements = parentElement.elements(childElementName);

        for (Element childElement : childElements) {
            String attributeValue = childElement.attributeValue(attributeName);
            if (attributeValue == null || attributeValue.trim().isEmpty()) {
                continue;
            }
            texts.add(attributeValue);
        }

        return texts;
    }

}
